package com.project.filter;

import com.project.model.User;
import com.project.service.UserService;
import com.project.util.MyJWT;
import com.project.util.Url;
import com.project.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(2)
@WebFilter(filterName = "checkLoginFilter", urlPatterns = "/*")
public class CheckLoginFilter implements Filter {
    @Autowired
    UserService userService;

    @Value("${app.key}")
    String appKey;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain filterChain
    ) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String excludePath = "/topics,/topics/\\d+$,/auth/*,/dist/*,/bootstrap/*,/plugins/*,/editor/*,/images/*,/\\w+$,/,/upload/*";
        String content = request.getRequestURI();
        boolean isExclude = Url.match(excludePath, content);
        String accessToken = Util.getCookieValueByName(request, "accessToken");
        String jwtSignatureToken = accessToken != null?userService.getCurrentJwtSignatureByPk(userService.getUserIdFromAccessToken(accessToken)):null;
        Boolean jwtVerify = false;
        if (accessToken != null && jwtSignatureToken != null) {
            jwtVerify = MyJWT.verifyJwt(accessToken, jwtSignatureToken);
        }

        if (isExclude || jwtVerify) {
            filterChain.doFilter(request, response);
        } else {
            response.setStatus(303);
            response.setHeader("Location", "/auth/login");
        }
    }

    @Override
    public void destroy() {

    }
}
